package com.kangtu.demofilter01.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
import javax.sound.midi.Soundbank;
import java.io.IOException;
import java.util.Enumeration;

/**
 * @program: demo-weix-pay
 * @description: LogCostFilter2
 * @author: 亮子说编程
 * @create: 2021-03-08 17:48
 **/

@WebFilter(urlPatterns = "/*", filterName = "logFilter2")
public class LogCostFilter2 implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void destroy() {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //--1
//        long start = System.currentTimeMillis();
//        filterChain.doFilter(servletRequest,servletResponse);
//        System.out.println("filer2="+(System.currentTimeMillis()-start));
        // 遍历参数
        Enumeration<String> parameterNames = servletRequest.getParameterNames();
        while (parameterNames.hasMoreElements()){
            System.out.println(parameterNames.nextElement());
        }

        //--2
        HttpServletRequest httpRequest = (HttpServletRequest)servletRequest;
        HttpServletResponseWrapper httpResponse = new HttpServletResponseWrapper((HttpServletResponse) servletResponse);
        System.out.println(httpRequest.getRequestURI());

        //
        Enumeration<String> names = httpRequest.getParameterNames();
        while(names.hasMoreElements()) {
            System.out.println(names.nextElement());
        }

        String token = httpRequest.getHeader("Authorization");
        System.out.println("token="+token);


        String path=httpRequest.getRequestURI();
        if(path.indexOf("/api/")<0){
            path="/api"+path;
            System.out.println(path);
            // 修改url后进行转发
            httpRequest.getRequestDispatcher(path).forward(servletRequest,servletResponse);
            return;
        }
        else {
            filterChain.doFilter(servletRequest,servletResponse);
        }
        return;
    }
}
